<template>
  <!--Dialog-->
  <Dialog v-model="modelValue">
    <el-form :status-icon="true" :model="addForm" label-width="auto" ref="addFormRef">
      <el-form-item label="上级组织" prop="parentId">
        <OrganizationSelect
          v-model="addForm.parentId"
          @change="onsetSelectedNode"
          style="width: 256px"
        />
      </el-form-item>
      <el-form-item
        label="名称"
        prop="displayName"
        :rules="[{ required: true, message: '请输入组织名称' }]"
      >
        <el-input
          v-model="addForm.displayName"
          placeholder="请输入组织名称"
          maxlength="256"
          style="width: 256px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSavue(addFormRef)" :loading="isLoading">保存</el-button>
      <el-button @click="onClose">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { OrganizationSelect } from '../../select/index';
import { createAsync } from '@/utils/api/organization/index';
import { Dialog } from '@/components/dialog/index';
import { propTypes } from '@/utils/propTypes';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { CreateOrganizationDto } from '@/utils/api/organization/type';
import type { ValidateFieldsError } from 'async-validator/dist-types';

let $emit = defineEmits(['update:refresh']);
// 刷新父组件
const refresh = () => {
  $emit('update:refresh');
};

// 组织选择后的业务逻辑
const onsetSelectedNode = (val: any) => {
  addForm.value.parentId = val[val.length - 1];
};

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));
const close = () => {
  modelValue.value = false;
};
// 保存Loading效果状态
const isLoading = ref<boolean>(false);

// 关闭
const onClose = () => {
  //触发自定义事件
  close();
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        try {
          isLoading.value = true;

          await createAsync(addForm.value);

          // 关闭弹窗
          close();

          // 提示成功
          ElMessage({
            showClose: true,
            message: '添加成功',
            type: 'success'
          });

          // 刷新父组件
          refresh();
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage({
                showClose: true,
                message: (error as Error).message,
                type: 'error'
              });
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};

// 组件实例
const addFormRef = ref<FormInstance>();
// 添加角色对象
const addForm = ref<CreateOrganizationDto>({
  displayName: ''
});
</script>
<style scoped lang="scss"></style>
